<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="excel-id">
        <el-input v-model="form.excelid"></el-input>
      </el-form-item>
      <el-form-item label="表头行号">
        <el-input v-model="headindex"></el-input>
      </el-form-item>
        <el-collapse v-model="activeName" accordion style="width: 200px ">
          <el-collapse-item name="1">
            <template slot="title">
              查询<div style="display: inline-block; width: 130px"></div><i class="el-icon-search" style="color: #f4516c" />
            </template>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button>取消</el-button>
          </el-collapse-item>
        </el-collapse>
    </el-form>

    <hr>
    <br>

    <div class="table_box">
      <el-table :data="formattedData" style="width: 100%">
        <el-table-column v-for="(col, index) in columns" :key="index" :prop="col.key"
                         :label="col.label"></el-table-column>
      </el-table>
    </div>

  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  props: ['id'],
  data() {
    return {
      jsonData: [],
      columns: [],
      headindex: 1,
      form: {
        excelid: ''
      },

      activeName: 1,

    }
  },
  mounted() {
    this.generateColumns()
    this.form.excelid = this.$store.state.excel.excelid
  },
  watch: {
    '$store.state.excel.excelid': function(val, oldVal) {
      console.log('watch:', val, oldVal)
      this.form.excelid = this.$store.state.excel.excelid
      this.onSubmit();
    }
  },
  methods: {

    onSubmit() {
      request.get(`/gu/excel/getExcelInfo?excelId=${this.form.excelid}`).then(response => {
        this.jsonData = [];
        this.jsonData = response;
        this.generateColumns();
        console.log('submit!');
      });
    },

    generateColumns() {
      if (this.jsonData.length > 0) {
        console.log(this.jsonData);
        const headers = this.jsonData[this.headindex - 1];
        console.log("headers:", headers)
        this.columns = Object.keys(headers).map((key, index) => {
          return {
            key: `col_${index}`,
            label: headers[`col_${index}`]
          };
        });
      }
    }
  },
  computed: {
    formattedData() {
      if (this.jsonData.length > 0) {
        return this.jsonData.map(item => {
          const formattedItem = {};
          Object.keys(item).forEach((key, index) => {
            formattedItem[`col_${index}`] = item[`col_${index}`];
          });
          return formattedItem;
        });
      } else {
        return [];
      }
    }
  }
};
</script>

<style scoped>

.table_box {
  overflow-y:auto;
  width: 100%;
  height: 500px;
}

</style>
